package com.example.xianglilai_end.Utils;

import com.alibaba.fastjson.JSONObject;
import lombok.Value;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.Map;

@Component
public class LocationUtil {
    /* 日志对象 */
    private static final Logger logger = LoggerFactory.getLogger(LocationUtil.class);
    private static String KEY = "be4fc29db2e087233ef876072fe4c1a8";
    /* 逆地理编码的url */
    public static final String COUNTER_LOCATION_URL = "https://restapi.amap.com/v3/geocode/regeo?parameters";

    /* 逆地理编码 */
    public static String getCounterLocation(String location){
        JSONObject jsonObject = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String city = "";
        // 创建URI对象，并且设置请求参数
        try {
            URI uri = getBuilderCounterLocation(COUNTER_LOCATION_URL, location);
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            CloseableHttpResponse response = httpclient.execute(httpGet);

            // 判断返回状态是否为200
            jsonObject = getCounterLocation(response);
            city = String.valueOf(jsonObject.getJSONObject("addressComponent").get("province"));
            httpclient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return city;
    }

    /* 逆地理编码封装URI */
    private static URI getBuilderCounterLocation(String url, String location) throws Exception{

        URIBuilder uriBuilder = new URIBuilder(url);
        // 公共参数
        uriBuilder.setParameter("key", KEY);
        uriBuilder.setParameter("location", location);

//        logger.info("请求的参数为:{}", JSONObject.toJSONString(uriBuilder));
        URI uri = uriBuilder.build();
        return uri;
    }

    private static JSONObject getCounterLocation(CloseableHttpResponse response) throws Exception{
        JSONObject regeocode = null;
        // 判断返回状态是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
//            logger.info("调用高德地图接口返回的结果为:{}",content);
            JSONObject jsonObject = (JSONObject) JSONObject.parse(content);
            regeocode =  (JSONObject)jsonObject.get("regeocode");

//            logger.info("返回的结果为:{}",JSONObject.toJSONString(regeocode));
        }
        return regeocode;
    }
}
